package top.huhuiyu.teachproject.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtUtils {
  private static final String PASSWORD = "top.huhuiyu.teachproject.jwt.password";

  private static final int EXPIRATION_TIME = 7 * 24 * 60 * 60 * 1000;
  public static final String USER_ID = "userId";

  public static String makeUserIdToken(Integer userId) {
    Date date = new Date();
    long expire = date.getTime() + EXPIRATION_TIME;
    date.setTime(expire);
    return JWT.create().withExpiresAt(date).withClaim(USER_ID, userId).sign(Algorithm.HMAC256(PASSWORD));
  }

  public static Integer parseUserIdToken(String token) {
    if (!StringUtils.hasText(token)) {
      return null;
    }
    try {
      return JWT.require(Algorithm.HMAC256(PASSWORD)).build().verify(token).getClaim(USER_ID).asInt();
    } catch (Exception ex) {
      return null;
    }
  }

}
